package com.xqboss.web.controller.nft;

import cn.hutool.core.util.ObjUtil;
import com.xqboss.apps.domain.nft.NftOld;
import com.xqboss.apps.vo.nft.NftOldVO;
import com.xqboss.apps.dto.nft.ChainLevelDTO;
import com.xqboss.apps.dto.nft.NftOldDTO;
import com.xqboss.apps.mapper.member.SysUserNftMapper;
import com.xqboss.apps.service.nft.NftOldService;
import com.xqboss.apps.util.mh.MoneyUtils;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.AjaxResult;
import com.xqboss.common.core.page.TableDataInfo;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;

/**
 * nftController
 *
 * @author xqboss
 * @date 2023-08-02
 */
//@RestController
//@RequestMapping("/web/nft-old")
public class WebNftOldController extends BaseController {

    @Autowired
    private NftOldService nftOldService;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private SysUserNftMapper sysUserNftMapper;

    /**
     * 查询nft列表
     */
    @GetMapping("/list-page")
    public TableDataInfo list(@RequestParam(name = "keyword", required = false, defaultValue = "") String keyword,
                              @RequestParam(name = "saleOut", required = false, defaultValue = "") Integer saleOut,
                              @RequestParam(name = "status", required = false, defaultValue = "") Integer status,
                              @RequestParam(name = "seriesId", required = false, defaultValue = "") Integer seriesId,
                              @RequestParam(name = "levelId", required = false, defaultValue = "") Integer levelId,
                              @RequestParam(name = "isPets", required = false, defaultValue = "") Integer isPets,
                              @RequestParam(name = "nftType", required = false, defaultValue = "") Integer nftType,
                              @RequestParam(name = "isBind", required = false, defaultValue = "") Integer isBind,
                              @RequestParam(name = "cateId", required = false) Integer cateId) {
        NftOld nftOld = new NftOld();
        nftOld.setChainSeriesId(ObjUtil.isNull(seriesId) ? null : Long.valueOf(seriesId));
        nftOld.setTitle(keyword);
        nftOld.setNftType(nftType);
        if (ObjUtil.equal(saleOut, 0)) {
            nftOld.setStock(1);
        } else if (ObjUtil.equal(saleOut, 1)){
            nftOld.setStock(0);
        }
        if (ObjUtil.isNotNull(status)) {
            switch (status) {
                case 0:
                case 1:
                    nftOld.setIsOnline(status);
                    break;
                case 2:
                    Calendar calendar = Calendar.getInstance();
                    nftOld.setPublishEndTime(calendar.getTime());
                    break;
                default:
                    break;
            }
        }
//        nft.setLevelId(levelId);
//        if (ObjUtil.equal(isBind, 1)) {
//            nft.setExtraStock(0);
//        }
//        if (ObjUtil.equal(isPets, 1)) {
//            nft.setNftType(2);
//        }
        startPage();
        List<NftOld> list = nftOldService.selectNftList(nftOld);
//        List<Long> idS = list.stream().map(Nft::getId).collect(Collectors.toList());
//        List<SysMemberNft> nfts = memberNftService.list(new QueryWrapper<SysMemberNft>()
//                .select("nft_id,id,self_accretion_str")
//                .lambda()
//                .in(CollectionUtils.isNotEmpty(idS), SysMemberNft::getNftId, idS)
//                .in(SysMemberNft::getRevenueExpenType, Arrays.asList(SysMemberNft.SysMemberNftEnum.接收.value,
//                        SysMemberNft.SysMemberNftEnum.取消转卖.value, SysMemberNft.SysMemberNftEnum.购买.value)));
//        List<Long> idF = nfts.stream().map(SysMemberNft::getNftId).collect(Collectors.toList());
//        Map<Long, List<SysMemberNft>> map = nfts.stream().collect(Collectors.groupingBy(SysMemberNft::getNftId));
//        if (idS.size() != idF.size()) {
//            for (Long id : idS) {
//                if (CollectionUtils.isEmpty(map.get(id))) {
//                    map.put(id, new ArrayList<>());
//                }
//            }
//        }
//
//        List<Nft> nftList = list.stream().map(item -> {
//                    item.setCirculationNum(nftService.nftCirculate(item.getId()).getNum());
//                    if (map.get(item.getId()) != null) {
//                        item.setHoldCount(map.get(item.getId()).size());
//                    }
//                    Integer surplusStock = redisCache.getListSize("self_accretion_" + item.getId()).intValue();
//                    item.setSurplusStock(surplusStock);
//                    SysMemberNft sysMemberNft = memberNftService.getOne(new LambdaQueryWrapper<SysMemberNft>()
//                            .eq(SysMemberNft::getNftId, item.getId()).last("limit 1"));
//                    if (sysMemberNft != null) {
//                        item.setIsBind(1);
//                    }
//                    Integer num = nftService.queryNumberOfHolders(item.getId()) == null ? 0 : nftService.queryNumberOfHolders(item.getId());
//                    item.setNumberOfHolders(num);
//                    Integer salesNum = sysMemberNftMapper.getSalesNum(item.getId());
//                    item.setSalesNum(salesNum);
//                    //查询藏品流通总量
//                    NftCirculateVO nftCirculateVO = nftService.nftCirculate(item.getId());
//                    item.setNum(nftCirculateVO.getNum());
//                    return item;
//                })
//                .collect(Collectors.toList());
//        list = nftList;
        return getDataTable(list);
    }

    /**
     * 导出nft列表
     */
    @Log(title = "nft", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, NftOld nftOld) {
        List<NftOld> list = nftOldService.selectNftList(nftOld);
        ExcelUtil<NftOld> util = new ExcelUtil<NftOld>(NftOld.class);
        util.exportExcel(response, list, "nft数据");
    }

    /**
     * 获取nft详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(nftOldService.selectNftById(id));
    }

    /**
     * 新增nft
     */
    @Log(title = "nft", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody NftOld nftOld) {
        return toAjax(nftOldService.insertNft(nftOld));
    }

    /**
     * 修改nft
     */
    @Log(title = "nft", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody NftOld nftOld) {
        return toAjax(nftOldService.updateNft(nftOld));
    }

    /**
     * 删除nft
     */
    @Log(title = "nft", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(nftOldService.deleteNftByIds(ids));
    }

    /**
     * 藏品等级
     */
    @GetMapping("/nft-levels")
    public AjaxResult nftLevels(@RequestParam(name = "targetType", required = false, defaultValue = "8") Integer targetType) {
        List<ChainLevelDTO> result = nftOldService.getNftLevel(targetType);
        return success(result);
    }

    /**
     * 创建nft 发布藏品
     */
    @PostMapping("/create")
    public AjaxResult create(@Validated @RequestBody NftOldDTO dto) {
        if (dto != null && dto.getIsFullReduce() != null && dto.getIsFullReduce() == 1) {
            BigDecimal sumAmount = MoneyUtils.add(dto.getIntegralCashAmount(), dto.getEnergyCashAmount());
            if (dto.getPrice().compareTo(sumAmount) != 0) {
                return error("满减抵扣的金额和商品不符合");
            }
        }
        nftOldService.createNft(dto);
        return success();
    }

    @GetMapping("/detail/{id}")
    public AjaxResult detail(@PathVariable("id") Long id) {
        NftOldVO nftVO = nftOldService.detail(id);
        return success(nftVO);
    }

    @PutMapping("/update/{id}")
    public AjaxResult update(@Validated @RequestBody NftOldDTO dto,
                             @PathVariable("id") Long id) {
        nftOldService.editNft(dto, id);
        return success();
    }

}

